<template>
  <view ref="container" class="lazy-load-container">
    <template v-if="observeStatus">
      <view :style="{ width: props.width, height: props.height }">
        <slot></slot>
      </view>
    </template>
    <template v-else>
      {{ props.loadText }}
    </template>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineEmits } from "vue";
const props = defineProps({
  loadText: {
    type: String,
    default: "加载中",
  },
  width: {
    type: String,
    default: "auto",
  },
  height: {
    type: String,
    default: "auto",
  },
  // 是否启用隐藏，销毁dom
  // 就是如果不在视野里面是否销毁传入插槽的内容
  isHide: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["load", "hide"]);
/**@data */
// 全局化index值，第一次的时候不调用载入
const renderIndex = ref(0);
const observer = ref(null);
const observeStatus = ref(false);
/**@method */
const createObserver = () => {
  observer.value = uni
    .createIntersectionObserver(this)
    .relativeToViewport()
    .observe(".lazy-load-container", (res) => {
      // console.log(res.intersectionRatio, "dom展示状态");
      if (renderIndex.value === 0) return renderIndex.value++;
      if (res.intersectionRatio > 0) {
        loadContent();
      } else {
        hideContentHandle();
      }
      renderIndex.value++;
    });
};
/**@载入成功 */
const loadContent = () => {
  observeStatus.value = true;
  emit("load");
  // destroyObserver();
};
/* 隐藏dom **/
const hideContentHandle = () => {
  if (!props.isHide) return emit("hide");
  observeStatus.value = false;
  emit("hide");
};
/**
 * @description  销毁观察者
 */
const destroyObserver = () => {
  if (observer.value) {
    observer.value.disconnect();
    observer.value = null;
  }
};
onMounted(() => {
  setTimeout(() => {
    createObserver();
  });
});
/**销毁 */
onUnmounted(() => {
  destroyObserver();
});
</script>

<style scoped>
.lazy-load-container {
  min-height: 100px;
  /* 设置容器的最小高度，以便在未加载内容时显示占位符 */
}
</style>
